﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using Zen.Barcode;
using System.Reflection;
using Worktool.CODE_Chris.SQL_DATA;
using Worktool.CODE_Chris.DataSourceHelpers;

namespace Worktool
{
    public partial class Serials : Form
    {
        private SQL sql;
        private SerialsHelper helper;
        private Boolean isInit = true;

        bool print = true;
        PrintDocument label;
        private string changedSerialNumber = "";
        private string changedManufacturer = "";
        private string changedModel = "";
        String pkInstalledPrinters;

        public Serials()
        {
            InitializeComponent();
            this.Text = "Serials: " + Login.currentDBName; 
            init();
        }

        private void init()
        {
            sql = new SQL();
            helper = new SerialsHelper(dataGridView2, this);

            sql.sendSQL("dbo.updateSerials");

            fillElementsInit();
            fillTablesInit();

            isInit = false;
        }

        #region Init
        private void fillTablesInit()
        {
            try
            {
                helper.getData1();
            }
            catch (Exception e)
            {

            }
        }

        private void fillElementsInit()
        {
            // Drucker in das Auswahlfeld eintragen
            try
            {
                comboBox1.Items.Clear();
                comboBox1.DropDownHeight = 500;
                comboBox1.DropDownWidth = 300;
                for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
                {
                    pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];
                    comboBox1.Items.Add(pkInstalledPrinters);
                }
                for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
                {
                    if (Login.labelPrinterName == PrinterSettings.InstalledPrinters[i])
                    {
                        comboBox1.Text = Login.labelPrinterName;
                    }
                }
            }
            catch (Exception e)
            {
                //MessageBox.Show("Fehler beim Füllen der Druck Combo-Box. Stacktrace:\r\n\r\n" + e.StackTrace, "Fehler");
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, dataGridView2, new object[] { true });
        }
        #endregion

        #region Filtereinstellungen
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            {
                if (textBox1.Text == "" && textBox2.Text == "")
                {
                    if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = null;
                }
                else if (textBox1.Text == "" && textBox2.Text != "")
                {
                    if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = string.Format("Model LIKE '{0}'", (textBox2.Text + "*"));
                }
                else if (textBox1.Text != "" && textBox2.Text == "")
                {
                    if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = string.Format("Manufacturer LIKE '{0}'", (textBox1.Text + "*"));
                }
                else if (textBox1.Text != "" && textBox2.Text != "")
                {
                    if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = string.Format("manufacturer LIKE '{0}' AND model LIKE '{1}'", (textBox1.Text + "*"), (textBox2.Text + "*"));
                }
            }
        }
        #endregion

        #region Label drucken
        public void printLabel()
        {
            // Label ausdrucken
            if (comboBox1.Text != "")
            {
                label = new PrintDocument();
                PaperSize pS = new PaperSize("Custom Size", 620, 290);
                label.DefaultPageSettings.PaperSize = pS;
                label.PrinterSettings.PrinterName = comboBox1.Text;
                label.PrinterSettings.DefaultPageSettings.PaperSize = pS;
                label.PrintPage += new PrintPageEventHandler(label_PrintPage);

                if (print)
                {
                    for (int i = 0; i < Convert.ToInt32(comboBox2.Text); i++)
                    {
                        label.Print();
                    }
                }
            }
        }

        private void label_PrintPage(object sender, PrintPageEventArgs e)
        {

            SolidBrush brush = new SolidBrush(Color.Black);
            System.Drawing.Font header = new System.Drawing.Font(FontFamily.GenericSansSerif, 9.0F, FontStyle.Bold);
            Code128BarcodeDraw barcode128 = BarcodeDrawFactory.Code128WithChecksum;
            Image img;

            e.Graphics.DrawString("Manufacturer: " + changedManufacturer, header, brush, 5, 10);
            e.Graphics.DrawString("Model: " + changedModel, header, brush, 5, 30);
            e.Graphics.DrawString("SN: " + changedSerialNumber, header, brush, 5, 50);
            e.Graphics.DrawImage(Worktool.Properties.Resources.ASC_Logo_quadratisch, 200, 10, 30, 30);
            if (changedSerialNumber != null && changedSerialNumber != "")
            {
                img = barcode128.Draw(changedSerialNumber, 30);
                e.Graphics.DrawImage(img, 5, 70);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (print)
            {
                button1.Text = "Printing Off";
                button1.BackColor = Color.Red;
                print = !print;
            }
            else
            {
                button1.Text = "Printing On";
                button1.BackColor = Color.Green;
                print = !print;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            int a = 0;
            for (int i = 0; i < dataGridView2.SelectedCells.Count; i++)
            {

                a = dataGridView2.SelectedCells[i].RowIndex;
                changedSerialNumber = dataGridView2.Rows[a].Cells["Serial Number"].Value.ToString();
                changedManufacturer = dataGridView2.Rows[a].Cells["Manufacturer"].Value.ToString();
                changedModel = dataGridView2.Rows[a].Cells["Model"].Value.ToString();

                label = new PrintDocument();
                PaperSize pS = new PaperSize("Custom Size", 620, 290);
                label.DefaultPageSettings.PaperSize = pS;
                label.PrinterSettings.PrinterName = comboBox1.Text;
                label.PrinterSettings.DefaultPageSettings.PaperSize = pS;
                label.PrintPage += new PrintPageEventHandler(label_PrintPage);
                try
                {
                    label.Print();
                }
                catch (Exception ex)
                {

                }
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Login.labelPrinterName = comboBox1.Text;
            Properties.Settings.Default.Save();
        }
        #endregion

        #region Export
        private void button4_Click(object sender, EventArgs e)
        {
            dataGridView2.SelectAll();
            DataObject dataObj = dataGridView2.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            xlexcel.Visible = true;
            xlWorkBook = xlexcel.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
            dataGridView2.ClearSelection();
        }
        #endregion

        #region Daten neu laden
        public void reloadAllData()
        {
            Cursor.Current = Cursors.WaitCursor;
            this.Enabled = false;
            fillElementsInit();
            fillTablesInit();
            this.Enabled = true;
            Cursor.Current = Cursors.Default;
        }
        #endregion

        #region Log-Daten öffnen
        private void button3_Click(object sender, EventArgs e)
        {
            Serials_log serials_log = new Serials_log();
            serials_log.Show();
        }
        #endregion
    }
}
